package name.matthewgreet.example2.common; import java.util.Arrays; import java.util.EnumSet; import java.util.List; /** * Provides support for enums when used as option parameters for the transformation of Entities into Data Transfer * Objects. If the enum has an 'ALL' value then it will be used to select all options. * * @param O An enum type used for options */ public class OptionEnum<O extends Enum<O>> { private EnumSet<O> optionSet; private Class<O> optionClass; @SuppressWarnings("unused") private OptionEnum() { super(); } /** * Constructs this Options with a default empty set; isRequested(Option) will always return false. Use setOptions * to add the options to this class. */ public OptionEnum(Class<O> cls) { this.optionClass = cls; } /** * Add one or many options to this class. If the options parameter contains an * option ALL then all the options will be used and contains() will always return true. * @param options if null then isRequested(Option) will always return false. */ @SuppressWarnings("unchecked") public void setOptions(O...options) { if (options == null || options.length == 0) optionSet = EnumSet.noneOf(optionClass); else if (containsAll(options)) optionSet = EnumSet.allOf(optionClass); else { List<O> list = Arrays.asList(options); optionSet = EnumSet.copyOf(list); } } /** * Tests if the passed in option has been requested. * @return True if the passed in option is in the internal set. */ public boolean isRequested(O option) { if (optionSet == null) return false; return optionSet.contains(option); } /** Test if there is an 'ALL' option for the enum in the array */ private boolean containsAll(O[] oo) { for (O o : oo) { if (o.name().equals("ALL")) return true; } return false; } @Override public String toString() { return "OptionEnum [optionSet=" + optionSet + ", optionClass=" + optionClass + "]"; } }